package com.chenc.javathreads.controlleraop.intercetor;

import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

import static com.chenc.javathreads.common.NormalInteceptorEnum.RESPONSE_BODY;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2023/12/27 16:15
 * @Version 1.0
 */
@ControllerAdvice
public class ControllerReponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        Method method = returnType.getMethod();
        String simpleName = converterType.getSimpleName();
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body != null) {
            try {
                HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
                servletRequest.setAttribute(RESPONSE_BODY.getValue(),JSONUtil.toJsonStr(body));
            }catch(Exception e){

            }
        }
        return body;
    }
}
